/*
 * sqlhandle.h
 *
 *  Created on: Dec 9, 2010
 *      Author: khanton
 */

#ifndef SQLHANDLE_H_
#define SQLHANDLE_H_

#include "sqlpool.h"
#include "con_state.h"

class controllers_network;

struct log_event
{
		typedef enum
		{
			le_main = 0,
			le_controller = 1,
			le_debug = 2
		} log_event_type_t;

		typedef enum
		{
			et_normal	= 0,
			et_state_change	= 1,
			et_critical	= 2
		} log_importance_t;
		
		typedef std::list<log_event> log_event_list_t;

		log_event(log_event_type_t le_,	con_state::controller_id _cont,  log_importance_t _imp, const std::string &_message, const std::string &_user, unsigned int _fault);

		static log_event message(log_importance_t _imp, const std::string &_message, const std::string &_user);

		static log_event controller(con_state::controller_id _cont,  log_importance_t _imp, const std::string &_message, const std::string &_user);
		static log_event controller(con_state::controller_id _cont,  log_importance_t _imp, const std::string &_message);
		static log_event controller(con_state::controller_id _cont,  log_importance_t _imp, const std::string &_message, unsigned int _fault);

		static log_event debug(log_importance_t _imp, const std::string &_message, const std::string &_user);

		log_event_type_t le_;
		con_state::controller_id cont_;
		log_importance_t imp_;

		std::string message_;
		std::string user_;

		unsigned int fault_;
};

class sqlhandle
{
	public:
		sqlhandle();
		virtual ~sqlhandle();

		void start(const std::string &_host, const std::string &_user, const std::string &_password, const std::string &_database);

		void close();

		bool create_controller_on_network(const con_state::controller_id _controller, std::string &_key);
		
		void delete_controller_from_network(const con_state::controller_id _controller);
		
		void dump_query(const std::string &_query) const;
		
		void set_controller_state(const con_state::controller_id _id, const con_state &_new_state, const con_state &_old_state);

		bool get_queue_cmd(int &_command, con_state::controller_id &_id, int &_param, std::string &_user);
		
		bool get_controller_program(const con_state::controller_id _id, std::string &_program);
		
		bool start_program_update(const con_state::controller_id _id);
		
		bool end_program_update(const con_state::controller_id _id, bool _success);

		void log(const log_event &_event);

		void log(log_event::log_event_list_t _list);

	private:

		asud_connection_pool *pool_;
};

#endif /* SQLHANDLE_H_ */
